<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// 导入需要的图标组件
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 查询参数
const queryParams = reactive({
  name: '',
  status: ''
})

// 表单参数
const formData = reactive({
  id: '',
  name: '',
  code: '',
  parentId: 0,
  path: '',
  component: '',
  icon: '',
  sort: 0,
  status: 'enabled',
  type: 'menu', // menu, button
  permission: ''
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入菜单编码', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择菜单类型', trigger: 'change' }
  ],
  path: [
    { required: true, message: '请输入路由路径', trigger: 'blur' }
  ]
}

// 菜单类型选项
const menuTypeOptions = [
  { value: 'menu', label: '菜单' },
  { value: 'button', label: '按钮' }
]

// 图标选项
const iconOptions = ref([])

// 初始化图标选项
const initIconOptions = () => {
  iconOptions.value = Object.keys(ElementPlusIconsVue).map(name => ({
    name,
    component: ElementPlusIconsVue[name]
  }))
}

// 父级菜单选项
const parentMenuOptions = ref([])

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogType = ref('') // add 或 edit

// 表单引用
const formRef = ref(null)

// 获取菜单列表
const getMenuList = async () => {
  loading.value = true
  
  try {
    // 这里应该是实际的API调用
    // const response = await axios.get('/api/v1/menus', { params: queryParams })
    
    // 模拟数据
    setTimeout(() => {
      const mockData = [
        {
          id: 1,
          name: '仪表盘',
          code: 'dashboard',
          parentId: 0,
          path: '/',
          component: 'DashboardView',
          icon: 'Menu',
          sort: 1,
          status: 'enabled',
          type: 'menu',
          permission: '',
          children: []
        },
        {
          id: 2,
          name: '系统管理',
          code: 'system',
          parentId: 0,
          path: '/system',
          component: '',
          icon: 'Setting',
          sort: 2,
          status: 'enabled',
          type: 'menu',
          permission: '',
          children: [
            {
              id: 3,
              name: '用户管理',
              code: 'system:user',
              parentId: 2,
              path: '/users',
              component: 'system/UsersView',
              icon: 'User',
              sort: 1,
              status: 'enabled',
              type: 'menu',
              permission: '',
              children: [
                {
                  id: 7,
                  name: '用户新增',
                  code: 'system:user:add',
                  parentId: 3,
                  path: '',
                  component: '',
                  icon: '',
                  sort: 1,
                  status: 'enabled',
                  type: 'button',
                  permission: 'user:add',
                  children: []
                },
                {
                  id: 8,
                  name: '用户编辑',
                  code: 'system:user:edit',
                  parentId: 3,
                  path: '',
                  component: '',
                  icon: '',
                  sort: 2,
                  status: 'enabled',
                  type: 'button',
                  permission: 'user:edit',
                  children: []
                },
                {
                  id: 9,
                  name: '用户删除',
                  code: 'system:user:delete',
                  parentId: 3,
                  path: '',
                  component: '',
                  icon: '',
                  sort: 3,
                  status: 'enabled',
                  type: 'button',
                  permission: 'user:delete',
                  children: []
                }
              ]
            },
            {
              id: 4,
              name: '角色管理',
              code: 'system:role',
              parentId: 2,
              path: '/roles',
              component: 'system/RolesView',
              icon: 'Check',
              sort: 2,
              status: 'enabled',
              type: 'menu',
              permission: '',
              children: []
            },
            {
              id: 5,
              name: '菜单管理',
              code: 'system:menu',
              parentId: 2,
              path: '/menus',
              component: 'system/MenusView',
              icon: 'Menu',
              sort: 3,
              status: 'enabled',
              type: 'menu',
              permission: '',
              children: []
            }
          ]
        },
        {
          id: 6,
          name: '个人信息',
          code: 'profile',
          parentId: 0,
          path: '/profile',
          component: 'ProfileView',
          icon: 'User',
          sort: 3,
          status: 'enabled',
          type: 'menu',
          permission: '',
          children: []
        }
      ]
      
      // 过滤查询条件
      let filteredData = [...mockData]
      if (queryParams.name) {
        const filterMenus = (menus, name) => {
          return menus.filter(menu => {
            if (menu.children && menu.children.length) {
              menu.children = filterMenus(menu.children, name)
            }
            return menu.name.includes(name) || (menu.children && menu.children.length > 0)
          })
        }
        filteredData = filterMenus(filteredData, queryParams.name)
      }
      
      if (queryParams.status) {
        const filterMenus = (menus, status) => {
          return menus.filter(menu => {
            if (menu.children && menu.children.length) {
              menu.children = filterMenus(menu.children, status)
            }
            return menu.status === status || (menu.children && menu.children.length > 0)
          })
        }
        filteredData = filterMenus(filteredData, queryParams.status)
      }
      
      tableData.value = filteredData
      loading.value = false
      
      // 构建父级菜单选项
      buildParentMenuOptions(mockData)
    }, 500)
  } catch (error) {
    console.error('获取菜单列表失败:', error)
    loading.value = false
  }
}

// 构建父级菜单选项
const buildParentMenuOptions = (menus, parentOptions = []) => {
  parentOptions.push({ id: 0, name: '顶级菜单' })
  
  const buildOptions = (menus, options) => {
    menus.forEach(menu => {
      if (menu.type === 'menu') {
        options.push({ id: menu.id, name: menu.name })
      }
      if (menu.children && menu.children.length) {
        buildOptions(menu.children, options)
      }
    })
  }
  
  buildOptions(menus, parentOptions)
  parentMenuOptions.value = parentOptions
}

// 处理查询
const handleQuery = () => {
  getMenuList()
}

// 处理重置
const handleReset = () => {
  queryParams.name = ''
  queryParams.status = ''
  handleQuery()
}

// 处理添加
const handleAdd = (row) => {
  resetForm()
  dialogTitle.value = '添加菜单'
  dialogType.value = 'add'
  
  // 如果有父级菜单，设置父级ID
  if (row && row.id) {
    formData.parentId = row.id
  }
  
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  resetForm()
  dialogTitle.value = '编辑菜单'
  dialogType.value = 'edit'
  
  // 填充表单数据
  Object.assign(formData, row)
  
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (row) => {
  if (row.children && row.children.length) {
    ElMessage.warning('该菜单下有子菜单，不能删除')
    return
  }
  
  ElMessageBox.confirm(`确定要删除菜单 ${row.name} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 这里应该是实际的API调用
      // await axios.delete(`/api/v1/menus/${row.id}`)
      
      // 模拟成功
      ElMessage.success('删除成功')
      getMenuList()
    } catch (error) {
      console.error('删除菜单失败:', error)
      ElMessage.error('删除失败，请稍后再试')
    }
  }).catch(() => {})
}

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          // 添加菜单
          // await axios.post('/api/v1/menus', formData)
          ElMessage.success('添加成功')
        } else {
          // 编辑菜单
          // await axios.put(`/api/v1/menus/${formData.id}`, formData)
          ElMessage.success('编辑成功')
        }
        
        dialogVisible.value = false
        getMenuList()
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败，请稍后再试')
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  formData.id = ''
  formData.name = ''
  formData.code = ''
  formData.parentId = 0
  formData.path = ''
  formData.component = ''
  formData.icon = ''
  formData.sort = 0
  formData.status = 'enabled'
  formData.type = 'menu'
  formData.permission = ''
  
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 格式化状态
const formatStatus = (status) => {
  const statusMap = {
    enabled: '启用',
    disabled: '禁用'
  }
  return statusMap[status] || status
}

// 格式化菜单类型
const formatMenuType = (type) => {
  const typeMap = {
    menu: '菜单',
    button: '按钮'
  }
  return typeMap[type] || type
}

onMounted(() => {
  getMenuList()
  initIconOptions()
})
</script>

<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="菜单名称">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入菜单名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="enabled" />
            <el-option label="禁用" value="disabled" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 操作区域 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <el-button type="primary" @click="handleAdd()">添加菜单</el-button>
        </div>
      </template>
      
      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        row-key="id"
        border
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="name" label="菜单名称" width="180" />
        <el-table-column prop="code" label="菜单编码" width="180" />
        <el-table-column prop="path" label="路由路径" />
        <el-table-column prop="component" label="组件路径" />
        <el-table-column prop="icon" label="图标" width="100">
          <template #default="scope">
            <el-icon v-if="scope.row.icon">
              <component :is="scope.row.icon" />
            </el-icon>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.type === 'menu' ? 'primary' : 'success'">
              {{ formatMenuType(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="permission" label="权限标识" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'enabled' ? 'success' : 'danger'">
              {{ formatStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handleAdd(scope.row)"
              v-if="scope.row.type === 'menu'"
            >
              添加子菜单
            </el-button>
            <el-button
              type="primary"
              link
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      append-to-body
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="上级菜单">
          <el-select v-model="formData.parentId" placeholder="请选择上级菜单" style="width: 100%">
            <el-option
              v-for="item in parentMenuOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="formData.type">
            <el-radio
              v-for="item in menuTypeOptions"
              :key="item.value"
              :label="item.value"
            >
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入菜单名称" />
        </el-form-item>
        
        <el-form-item label="菜单编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入菜单编码" />
        </el-form-item>
        
        <el-form-item label="路由路径" prop="path" v-if="formData.type === 'menu'">
          <el-input v-model="formData.path" placeholder="请输入路由路径" />
        </el-form-item>
        
        <el-form-item label="组件路径" prop="component" v-if="formData.type === 'menu'">
          <el-input v-model="formData.component" placeholder="请输入组件路径" />
        </el-form-item>
        
        <el-form-item label="权限标识" prop="permission" v-if="formData.type === 'button'">
          <el-input v-model="formData.permission" placeholder="请输入权限标识" />
        </el-form-item>
        
        <el-form-item label="图标" prop="icon" v-if="formData.type === 'menu'">
          <el-select v-model="formData.icon" placeholder="请选择图标" filterable style="width: 100%">
            <el-option
              v-for="icon in iconOptions"
              :key="icon.name"
              :label="icon.name"
              :value="icon.name"
            >
              <div style="display: flex; align-items: center;">
                <el-icon><component :is="icon.name" /></el-icon>
                <span style="margin-left: 8px;">{{ icon.name }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" :max="999" />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="enabled">启用</el-radio>
            <el-radio label="disabled">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.app-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 